package com.jml.zlhq.app.ui;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.http.Header;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshBase.Mode;
import com.handmark.pulltorefresh.library.PullToRefreshBase.OnRefreshListener;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.jml.zlhq.app.BuildConfig;
import com.jml.zlhq.app.R;
import com.jml.zlhq.app.URLs;
import com.jml.zlhq.app.adapter.IBaseAdapter;
import com.jml.zlhq.app.adapter.MainFaXianAdapter;
import com.jml.zlhq.app.service.HttpService;
import com.jml.zlhq.app.util.BaseTools;
import com.jml.zlhq.app.util.UIUtil;
import com.loopj.android.http.TextHttpResponseHandler;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.format.DateUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;

public class HuodongFragment extends BaseFragment {
	private int huodong = 1;
	private Map<String,String> params = new HashMap<String, String>();
	//一个带下拉刷新的listview
	private PullToRefreshListView mPullToRefreshView;
	private ListView listView;
	private IBaseAdapter adapter;
	private List<JSONObject> listItems = new ArrayList<JSONObject>();
	
	@SuppressLint("HandlerLeak")
	private Handler mHandler = new Handler(){
		@Override
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case 1:
				adapter.notifyDataSetChanged();
				mPullToRefreshView.onRefreshComplete();
				if(pageEnd)mPullToRefreshView.setMode(Mode.PULL_FROM_START);
				break;
			default:
				break;
			}
		}
	};
	
	public HuodongFragment(int huodong) {
		super();
		this.huodong = huodong;
		switch (this.huodong) {
		case 1:
			params.put("category", "理财大厅");
			params.put("tags", "jingpin");
			params.put("page", "1");
			break;
		case 2:
			params.put("category", "理财大厅");
			params.put("tags", "fanxian");
			params.put("page", "1");		
			break;
		case 3:
			params.put("category", "理财大厅");
			params.put("tags", "0_10");
			params.put("page", "1");
			break;
		case 4:
			params.put("category", "理财大厅");
			params.put("tags", "10_100");
			params.put("page", "1");
			break;
		case 5:
			params.put("category", "理财大厅");
			params.put("tags", "all");
			params.put("page", "1");
			break;
		}
	}
	
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		super.onCreateView(inflater, container, savedInstanceState);
		pageView.findViewById(R.id.content_header).setVisibility(View.GONE);
		//PullToRefreshListView引入的一个下拉listview刷新组件
		mPullToRefreshView = (PullToRefreshListView) pageView.findViewById(R.id.main_faxian_listview);
		//设置setOnRefreshListener刷新监听
		mPullToRefreshView.setOnRefreshListener(new OnRefreshListener<ListView>() {
			//该监听存在的onrefresh方法
			@Override
			public void onRefresh(PullToRefreshBase<ListView> refreshView) {
				if(PullToRefreshBase.Mode.PULL_FROM_START == mPullToRefreshView.getCurrentMode()){
					String label = DateUtils.formatDateTime(appContext,System.currentTimeMillis(),DateUtils.FORMAT_SHOW_TIME | DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_ABBREV_ALL);  
					mPullToRefreshView.getLoadingLayoutProxy().setLastUpdatedLabel(label);
					clearData();
					loadData(null);
				}else if(PullToRefreshBase.Mode.PULL_FROM_END == mPullToRefreshView.getCurrentMode()){
					if(urlParam==null)urlParam = new HashMap<String,String>();
					pageIndex++;
					loadData(urlParam);
				}
			}
		});
		//设置到listview列表视图上
		listView = mPullToRefreshView.getRefreshableView();
		//listView.setDividerHeight(UIUtil.dip2px(appContext, 10));
		adapter = new MainFaXianAdapter(activity, listItems,false);
		//实现装配
		listView.setAdapter(adapter);
		//装配列表每条数据的点击详情
		listView.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
			   /* int index = new Long(id).intValue();
                LingGanFragment.toweb(BaseTools.getFrom("_id", listItems.get(index)), appContext.getProperty("bToken"), activity);*/
			    int index = new Long(id).intValue();
				Bundle data  = new Bundle();
				data.putString("title", "活动详情");
				data.putString("id", BaseTools.getFrom("_id", listItems.get(index)));
				UIUtil.openActivity(activity, HuodongDetailActivity.class, data);
			}
		});
		
		loadData(null);
		
		return pageView;
	}

	@Override
	public void loadData(Map<String, String> param) {
		params.put("page", String.valueOf(pageIndex));
		HttpService.getByText(URLs.MAIN_ARTICLE, params, new TextHttpResponseHandler() {
			@Override
			public void onSuccess(int arg0, Header[] arg1, String resultStr) {
				try {
					if(BuildConfig.DEBUG)Log.i("==result post-huodong==", resultStr);
					JSONObject result = new JSONObject(resultStr);
					if(result.getInt("status")==0){
						JSONArray data = result.getJSONObject("data").getJSONArray("list");
						for (int i = 0; data!=null && i < data.length(); i++) {
							listItems.add(data.getJSONObject(i));
						}
						if(data==null||data.length()<=0){
							pageEnd = true;
							adapter.setPageEnd(pageEnd);
						}
					}else{
						if(pageIndex>0)pageIndex--;
					}
					mHandler.sendEmptyMessage(1);
					
				} catch (JSONException e) {
					e.printStackTrace();
				}
			}
			
			@Override
			public void onFailure(int arg0, Header[] arg1, String arg2, Throwable arg3) {
				UIUtil.ToastMessage(activity, "抱歉，访问失败");
			}
		});
		
	}

	@Override
	public void clearData() {
		pageEnd = false;
		listItems.clear();
		pageIndex = 0;
		adapter.setPageEnd(pageEnd);
		mPullToRefreshView.setMode(Mode.BOTH);
	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		
	}

	@Override
	protected int getPageView() {
		return R.layout.main_faxian_hd;
	}

}
